<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button class="filter-item" style="margin-left: 10px; float:right" round size="mini" @click="handleCreate">
        添加
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px; float:right" round size="mini" @click.prevent="delData">
        批量删除
      </el-button>
    </div>

    <el-table
      ref="table"
      :key="tableKey"
      v-loading="listLoading"
      :header-cell-style="{background:'#eef1f6',color:'#606266'}"
      stripe
      :data="list"
      highlight-current-row
      style="width: 100%;"
      @selection-change="selectRow"
    >
      <el-table-column type="selection" width="77" />
      <el-table-column label="序号" align="center" width="80">
        <template slot-scope="{$index}">
          <span>{{ $index+1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="类型名称" width="100px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.deviceTypeName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="类型单位" width="100px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.deviceTypeUnit }}</span>
        </template>
      </el-table-column>
      <el-table-column label="模块类型" min-width="90px">
        <template slot-scope="{row}">
          <span>{{ row.moduleType }}</span>
        </template>
      </el-table-column>
      <el-table-column label="类型编码" min-width="90px">
        <template slot-scope="{row}">
          <span>{{ row.typeCode }}</span>
        </template>
      </el-table-column>
      <el-table-column label="类型编号" min-width="90px">
        <template slot-scope="{row}">
          <span>{{ row.deviceTypeId }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最低预警" min-width="90px">
        <template slot-scope="{row}">
          <span>{{ row.minWarning }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最高预警" min-width="90px">
        <template slot-scope="{row}">
          <span>{{ row.maxWarning }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="text" size="medium" title="编辑" @click="handleUpdate(row)"><i class="el-icon-edit" />
          </el-button>
          <el-button size="medium" type="text" title="删除" @click="handleDelete(row)"><i class="el-icon-delete" />
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="25%">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="80px" style="width:300px;" size="mini">
        <el-form-item label="类型名称" prop="deviceTypeName">
          <el-input v-model="temp.deviceTypeName" />
        </el-form-item>
        <el-form-item label="类型单位" prop="deviceTypeUnit">
          <el-input v-model="temp.deviceTypeUnit" />
        </el-form-item>
        <el-form-item label="类型编码" prop="typeCode">
          <el-input v-model="temp.typeCode" />
        </el-form-item>
        <el-form-item label="模块类型" prop="moduleType">
          <el-select v-model="temp.moduleType" placeholder="请选择模块类型" clearable style="width: 120px" class="filter-item" @change="changeup">
            <el-option v-for="item in moduleTypeoption" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="isNeedAudit" label="最低预警值" prop="minWarning">
          <el-input v-model="temp.minWarning" />
        </el-form-item>
        <el-form-item v-if="isNeedAudit" label="最高预警值" prop="maxWarning">
          <el-input v-model="temp.maxWarning" />
        </el-form-item>
        <el-form-item v-if="isNeedAudit" label="预警解决方案" prop="solutionContent">
          <el-checkbox-group v-model="checkedmethods" @change="handleChange">
            <el-checkbox v-for="item in methodsoption" :key="item.value" :label="item.label">{{ item.label }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" size="mini" @click="dialogStatus==='create'?createData():updateData()">
          保存
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getTypeList, deleteTypeList, deleteTypeLists, updateTypeList, addTypeList } from '@/api/type'
import { getIdandName } from '@/api/alert'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { compile } from 'path-to-regexp'

export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      sels: [],
      isNeedAudit: true,
      checkedmethods: [],
      methodsoption: [],
      moduleTypeoption: ['传感器类', '视频监控类', '控制交互类', '气象站类'],
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20
        // title: undefined,
      },
      temp: {
        item: [],
        deviceTypeId: '',
        deviceTypeName: '',
        deviceTypeUnit: '',
        typeCode: '',
        moduleType: '',
        minWarning: '',
        maxWarning: '',
        solutionContent: []
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        // title: [{ required: true, message: 'title is required', trigger: 'blur' }],
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
    getIdandName().then(res => {
      for (let i = 0; i < res.data.length; i++) {
        this.methodsoption.push({ value: `${res.data[i].earlyWarningId}`, label: `${res.data[i].warningName}` })
      }
    })
  },
  methods: {
    changeup() {
      console.log(this.temp.moduleType)
      if (this.temp.moduleType == '视频监控类' || this.temp.moduleType == '控制交互类') {
        this.isNeedAudit = false
      } else {
        this.isNeedAudit = true
      }
    },
    handleChange(value) {
      console.log(value)
      this.temp.solutionContent = value
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    selectRow(sels) {
      this.sels = sels
    },
    // 批量删除
    delData() {
      this.$confirm(
        '确定要删除吗？删除后不能恢复',
        '系统提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        for (let i = 0; i < this.sels.length; i++) {
          this.temp.item[i] = this.sels[i].deviceTypeId
        }
        deleteTypeLists(this.temp)
        this.getList()
        this.$notify({
          title: 'Success',
          message: 'Update Successfully',
          type: 'success',
          duration: 2000
        })
        // this.getList()
      })
    },
    getList() {
      this.listLoading = true

      getTypeList(this.listQuery).then(response => {
        this.list = response.data.records
        this.total = response.data.total

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },

    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    resetTemp() {
      this.temp = {
        deviceTypeId: '',
        deviceTypeName: '',
        deviceTypeUnit: '',
        typeCode: '',
        moduleType: '',
        minWarning: '',
        maxWarning: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          addTypeList(this.temp).then(() => {
            // this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      // this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          // tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          console.log(tempData.deviceTypeId)
          updateTypeList(tempData).then(() => {
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Update Successfully',
              type: 'success',
              duration: 2000
            })
            // this.getList()
          })
        }
      })
    },
    // 删除
    handleDelete(row) {
      console.log(row)
      this.$confirm(
        '确定要删除吗？删除后不能恢复',
        '系统提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        deleteTypeList(row)
        this.getList()
        this.$notify({
          title: 'Success',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
        // this.getList()
      })
    },
    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    }
  }
}
</script>
